package com.drinkian.authentication.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.drinkian.authentication.entity.po.Role;
import com.drinkian.authentication.entity.po.User;
import com.drinkian.authentication.entity.po.UserRole;
import com.drinkian.authentication.entity.vo.VUserToChangeStatus;
import com.drinkian.authentication.entity.vo.VUserUpdate;
import com.drinkian.authentication.entity.bo.BUserWithRoleList;
import com.drinkian.authentication.entity.vo.VUserWithRole;
import com.drinkian.authentication.mapper.RoleMapper;
import com.drinkian.authentication.mapper.UserMapper;
import com.drinkian.authentication.mapper.UserRoleMapper;
import com.drinkian.authentication.service.IUserService;
import com.drinkian.entity.RequestResult;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public RequestResult updateUser(VUserUpdate vUserUpdate) {
        // 1、需要重新设置密码
        if (!StringUtils.isNullOrEmpty(vUserUpdate.getNewPassword())) {
            // 1.1、首先根据id从数据库中查询到密码进行比对，如果比对成功了，则可以修改密码，否则哒咩
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", vUserUpdate.getId());
            queryWrapper.eq("status", 2);
            User user = userMapper.selectOne(queryWrapper);
            boolean matched = bCryptPasswordEncoder.matches(vUserUpdate.getOriginPassword(), user.getPassword());
            if (!matched) {
                return new RequestResult(HttpStatus.BAD_REQUEST.value(), "原密码错误！");
            } else {
                vUserUpdate.setNewPassword(bCryptPasswordEncoder.encode(vUserUpdate.getNewPassword()));
            }
        } else {
            vUserUpdate.setNewPassword(null);
        }
        // 2、不管是不是需要重新设置密码，都需要更新一些基本信息
        int result = userMapper.updateUser(vUserUpdate);
        if (result != 1) {
            return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "更新数据库出错！");
        } else {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", vUserUpdate.getId());
            User user = userMapper.selectOne(queryWrapper);
            return new RequestResult(HttpStatus.OK.value(), user);
        }
    }

    @Override
    public RequestResult getNewUserList(Integer current, Integer size) {
        IPage<User> iPage = new Page<>(current, size);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("status", 1);
        IPage<User> userIPage = userMapper.selectPage(iPage, userQueryWrapper);
        return new RequestResult(HttpStatus.OK.value(), userIPage);
    }

    @Override
    public RequestResult permit(Long id) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id", id);
        userQueryWrapper.eq("status", 1);
        User user = userMapper.selectOne(userQueryWrapper);
        // 更新用户状态
        user.setStatus(2);
        int update = userMapper.updateById(user);
        // 添加基础角色
        userRoleMapper.insert(new UserRole(null, user.getId(), 3l, null, null, null, null));
        // 发送邮件通知
        if (update == 1) {
            String email = user.getEmail();
            // 设置邮件内容
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setSubject("HBUShop审核结果");
            simpleMailMessage.setText("审核通过！");
            // 设置邮件发送人、接收人
            simpleMailMessage.setFrom("2294422096@qq.com");
            simpleMailMessage.setTo(email);
            // 发送邮件
            javaMailSender.send(simpleMailMessage);
        }
        return new RequestResult(HttpStatus.OK.value(), "更新成功！");
    }

    @Override
    public RequestResult refuse(Long id) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id", id);
        userQueryWrapper.eq("status", 1);
        User user = userMapper.selectOne(userQueryWrapper);
        if (!Objects.isNull(user)) {
            String email = user.getEmail();
            // 设置邮件内容
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setSubject("HBUShop审核结果");
            simpleMailMessage.setText("审核未通过，请重新申请（注意用户名必须是学号或者教职工号，并且身份证明的照片必须带有您的学号或者职工号）！");
            // 设置邮件发送人、接收人
            simpleMailMessage.setFrom("2294422096@qq.com");
            simpleMailMessage.setTo(email);
            // 发送邮件
            javaMailSender.send(simpleMailMessage);
        }
        userMapper.delete(userQueryWrapper);
        return new RequestResult(HttpStatus.OK.value(), "驳回成功！");
    }

    @Override
    public RequestResult getAllUserAndRoleButSuperAdmin(Integer current, Integer size) {
        IPage<User> iPage = new Page<>(current, size);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        IPage<User> userIPage = userMapper.selectPage(iPage, userQueryWrapper);
        List<BUserWithRoleList> bUserWithRoleList = new LinkedList<>();
        Iterator<User> iterator = userIPage.getRecords().iterator();
        while (iterator.hasNext()) {
            User next = iterator.next();
            List<Role> roleLinkedList = new LinkedList<>();

            // 获取用户角色关联列表
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id", next.getId());
            userRoleQueryWrapper.eq("deleted", 0);
            List<UserRole> userRoleList = userRoleMapper.selectList(userRoleQueryWrapper);

            // 获取角色列表
            for (UserRole userRole : userRoleList) {
                QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
                roleQueryWrapper.eq("id", userRole.getRoleId());
                Role role = roleMapper.selectOne(roleQueryWrapper);
                roleLinkedList.add(role);
            }
            bUserWithRoleList.add(new BUserWithRoleList(next, roleLinkedList));
        }
        return new RequestResult(HttpStatus.OK.value(), new VUserWithRole((int) iPage.getTotal(), bUserWithRoleList));
    }

    @Override
    public RequestResult changeStatus(VUserToChangeStatus vUserToChangeStatus) {
        User user = vUserToChangeStatus.getUser();
        Integer status = vUserToChangeStatus.getStatus();
        if (user.getStatus() != status) {
            user.setStatus(status);
            int update = userMapper.updateById(user);
            if (update == 1) {
                return new RequestResult(HttpStatus.OK.value(), "修改成功！");
            } else {
                return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "修改失败！");
            }
        } else {
            return new RequestResult(HttpStatus.OK.value(), "修改成功！");
        }
    }
}
